package com.sh.caryr.erp.controller.product;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sh.caryr.erp.entity.PageResultMessage;
import com.sh.caryr.erp.entity.ResultMessage;
import com.sh.caryr.erp.entity.definition.CommonFieldDef;
import com.sh.caryr.erp.entity.product.CombNum;
import com.sh.caryr.erp.entity.product.ProductSpec;
import com.sh.caryr.erp.entity.stock.Sku;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.exception.RestServiceException;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.service.IProductSpecService;
import com.sh.caryr.erp.service.ISkuService;
import com.sh.caryr.erp.util.ERPConstants;
import com.sh.caryr.erp.util.MyBatisUtil;
import com.sh.caryr.erp.util.UtilityTool;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/productSpec")
@SessionAttributes("user")
public class ProductSpecController {

    private final IProductSpecService productSpecService;

    private final ISkuService skuService;

    @Autowired
    public ProductSpecController(IProductSpecService productSpecService, ISkuService skuService) {
        this.productSpecService = productSpecService;
        this.skuService = skuService;
    }

    @ApiOperation(value = "Get Count", notes = "Get Count")
    @RequestMapping(value = "/count", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @SuppressWarnings("unchecked")
    public ResultMessage<JSONObject> countProducts(@ModelAttribute("user") User operator) {
        Wrapper wrapper = MyBatisUtil.getIsActiveWrapper();
        MyBatisUtil.addAuthFilter(wrapper, operator, ERPConstants.AUTH_TARGET_PRODUCT, false, true);
        JSONObject counts = new JSONObject();
        counts.put(CommonFieldDef.FRONT_COUNT_TOTAL, productSpecService.selectCount(wrapper));
        counts.put(CommonFieldDef.FRONT_COUNT_FINISH, productSpecService.selectCount(wrapper.isNotNull(CommonFieldDef.PRODUCT_SPEC_SKU_ID)));
        return new ResultMessage<>(counts);
    }

    @Transactional
    @ApiOperation(value = "Generate Sku", notes = "Generate Sku")
    @ApiImplicitParam(name = "ids", value = "Product id", required = true, dataType = "String")
    @RequestMapping(value = "/genSku/{ids}", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @SuppressWarnings("unchecked")
    public ResultMessage genSku(@PathVariable String ids, @ModelAttribute("user") User operator) {
        List<Long> list = UtilityTool.convertStringArray2LongList(ids.split(","));
        try {
            Wrapper productSpecWrap = new EntityWrapper<CombNum>().in("productId", list);
            List<ProductSpec> productSpecList = productSpecService.selectList(productSpecWrap);
            List<Sku> skuList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(productSpecList)) {
                for (ProductSpec proSpec : productSpecList) {
                    if (proSpec.getSkuId() == null) {
                        Sku sku = copyProSpec2Sku(proSpec);
                        MyBatisUtil.updateCommonFields(sku, operator);
                        skuList.add(sku);
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(skuList)) {
                //Insert Sku
                skuService.insertBatch(skuList);
                //Update skuId of product specs
                for (Sku sku : skuList) {
                    for (ProductSpec spec : productSpecList) {
                        if (sku.getProductSpecId().equals(spec.getId())) {
                            spec.setSkuId(sku.getId());
                            break;
                        }

                    }
                }
                productSpecService.updateBatchById(productSpecList);
            }
            return new ResultMessage<>(skuList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RestServiceException(ResultCode.DELETE_NOT_FOUND);
        }
    }

    @ApiOperation(value = "获取 Product Spec 列表信息", notes = "获取Product Spec列表信息")
    @RequestMapping(method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @SuppressWarnings("unchecked")
    public ResultMessage<List<ProductSpec>> findProductSpecs(
            @RequestParam(required = false) String queryField,
            @RequestParam(required = false) String queryValue,
            @RequestParam(defaultValue = "id") String orderBy,
            @RequestParam(defaultValue = "false") Boolean isAsc,
            @ModelAttribute("user") User operator) {

        Wrapper wrapper = MyBatisUtil.getIsActiveWrapper(queryField, queryValue, orderBy, isAsc);
        MyBatisUtil.addAuthFilter(wrapper, operator, ERPConstants.AUTH_TARGET_PRODUCT, false, false);
        List<ProductSpec> records = productSpecService.findProductSpecsDynamic(wrapper);
        return new PageResultMessage<>(records, productSpecService.selectCount(wrapper));
    }

    private Sku copyProSpec2Sku(ProductSpec proSpec) {
        Sku sku = new Sku();
        sku.setProductId(proSpec.getProductId());
        sku.setProductSpecId(proSpec.getId());
        sku.setName(proSpec.getName());
        sku.setCode(proSpec.getCode());
        sku.setImg(proSpec.getImg());
        sku.setAttribute1(proSpec.getAttribute1());
        sku.setAttribute2(proSpec.getAttribute2());
        sku.setAttribute3(proSpec.getAttribute3());
        sku.setAttribute4(proSpec.getAttribute4());
        sku.setPurchasePrice(proSpec.getPurchasePrice());
        sku.setSalePrice(proSpec.getSalePrice());
        return sku;
    }
}
